<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="老人姓名" prop="elderName">
              <el-input v-model="queryParams.elderName" placeholder="请输入老人姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleStepInput" v-hasPermi="['nursing:healthCheck:add']">开始健康监测</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['nursing:healthCheck:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['nursing:healthCheck:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['nursing:healthCheck:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="healthCheckList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" align="center" prop="id" v-if="false" />
        <el-table-column label="老人姓名" align="center" prop="elderName" />
        <el-table-column label="检查人姓名" align="center" prop="doctor" />
        <el-table-column label="检查日期" align="center" prop="checkDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.checkDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="健康状态" align="center" prop="healthStatus">
          <template #default="scope">
            <dict-tag :options="sys_jkzt" :value="scope.row.healthStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleDetail(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['nursing:healthCheck:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['nursing:healthCheck:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改健康监测对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="healthCheckFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="老人姓名" prop="elderName">
          <el-input v-model="form.elderName" placeholder="请输入老人姓名" />
        </el-form-item>
        <el-form-item label="检查日期" prop="checkDate">
          <el-date-picker clearable
            v-model="form.checkDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择检查日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="身高(cm)" prop="height">
          <el-input v-model="form.height" placeholder="请输入身高(cm)" />
        </el-form-item>
        <el-form-item label="体重(kg)" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入体重(kg)" />
        </el-form-item>
        <el-form-item label="BMI指数" prop="bmi">
          <el-input v-model="form.bmi" placeholder="请输入BMI指数" />
        </el-form-item>
        <el-form-item label="收缩压(mmHg)" prop="bloodPressureHigh">
          <el-input v-model="form.bloodPressureHigh" placeholder="请输入收缩压(mmHg)" />
        </el-form-item>
        <el-form-item label="舒张压(mmHg)" prop="bloodPressureLow">
          <el-input v-model="form.bloodPressureLow" placeholder="请输入舒张压(mmHg)" />
        </el-form-item>
        <el-form-item label="脉搏(次/分)" prop="pulse">
          <el-input v-model="form.pulse" placeholder="请输入脉搏(次/分)" />
        </el-form-item>
        <el-form-item label="血糖(mmol/L)" prop="bloodSugar">
          <el-input v-model="form.bloodSugar" placeholder="请输入血糖(mmol/L)" />
        </el-form-item>
        <el-form-item label="血氧饱和度(%)" prop="bloodOxygen">
          <el-input v-model="form.bloodOxygen" placeholder="请输入血氧饱和度(%)" />
        </el-form-item>
        <el-form-item label="体温(℃)" prop="temperature">
          <el-input v-model="form.temperature" placeholder="请输入体温(℃)" />
        </el-form-item>
        <el-form-item label="心率(次/分)" prop="heartRate">
          <el-input v-model="form.heartRate" placeholder="请输入心率(次/分)" />
        </el-form-item>
        <el-form-item label="呼吸频率(次/分)" prop="respiratoryRate">
          <el-input v-model="form.respiratoryRate" placeholder="请输入呼吸频率(次/分)" />
        </el-form-item>
        <el-form-item label="血脂情况" prop="bloodLipid">
            <el-input v-model="form.bloodLipid" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="肝功能" prop="liverFunction">
            <el-input v-model="form.liverFunction" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="肾功能" prop="kidneyFunction">
            <el-input v-model="form.kidneyFunction" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="健康状态" prop="healthStatus">
          <el-select v-model="form.healthStatus" placeholder="请选择健康状态">
            <el-option
                v-for="dict in sys_jkzt"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="异常项目" prop="abnormalItems">
            <el-input v-model="form.abnormalItems" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="检查人姓名" prop="doctor">
          <el-input 
            v-model="form.doctor" 
            placeholder="请输入检查人姓名" 
            :disabled="userStore.roles.some(role => role === 'nurse') && !userStore.roles.some(role => role === 'admin_ms' || role === 'admin')"
          />
        </el-form-item>
        <el-form-item label="医疗建议" prop="suggestions">
            <el-input v-model="form.suggestions" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="下次检查日期" prop="nextCheckDate">
          <el-date-picker clearable
            v-model="form.nextCheckDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择下次检查日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="HealthCheck" lang="ts">
import { listHealthCheck, getHealthCheck, delHealthCheck, addHealthCheck, updateHealthCheck } from '@/api/nursing/healthCheck';
import { HealthCheckVO, HealthCheckQuery, HealthCheckForm } from '@/api/nursing/healthCheck/types';
import { useRouter } from 'vue-router';
import { useUserStoreHook } from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_jkzt } = toRefs<any>(proxy?.useDict('sys_jkzt'));
const router = useRouter();
const userStore = useUserStoreHook();

const healthCheckList = ref<HealthCheckVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const healthCheckFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: HealthCheckForm = {
  id: undefined,
  elderName: undefined,
  checkDate: undefined,
  height: undefined,
  weight: undefined,
  bmi: undefined,
  bloodPressureHigh: undefined,
  bloodPressureLow: undefined,
  pulse: undefined,
  bloodSugar: undefined,
  bloodOxygen: undefined,
  temperature: undefined,
  heartRate: undefined,
  respiratoryRate: undefined,
  bloodLipid: undefined,
  liverFunction: undefined,
  kidneyFunction: undefined,
  healthStatus: undefined,
  abnormalItems: undefined,
  doctor: undefined,
  suggestions: undefined,
  nextCheckDate: undefined,
  remarks: undefined,
}
const data = reactive<PageData<HealthCheckForm, HealthCheckQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    elderName: undefined,
    params: {
    }
  },
  rules: {
    id: [
      { required: true, message: "ID不能为空", trigger: "blur" }
    ],
    checkDate: [
      { required: true, message: "检查日期不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询健康监测列表 */
const getList = async () => {
  loading.value = true;
  const res = await listHealthCheck(queryParams.value);
  healthCheckList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  healthCheckFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: HealthCheckVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加健康监测";
  // 如果是护理员用户，自动填入当前用户昵称
  if (userStore.roles.some(role => role === 'nurse') && !userStore.roles.some(role => role === 'admin_ms' || role === 'admin')) {
    form.value.doctor = userStore.nickname;
  }
}

/** 修改按钮操作 */
const handleUpdate = async (row?: HealthCheckVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getHealthCheck(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改健康监测";
}

/** 提交按钮 */
const submitForm = () => {
  healthCheckFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateHealthCheck(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addHealthCheck(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: HealthCheckVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除健康监测编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delHealthCheck(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('nursing/healthCheck/export', {
    ...queryParams.value
  }, `healthCheck_${new Date().getTime()}.xlsx`)
}

/** 开始健康监测按钮操作 */
const handleStepInput = () => {
  try {
    // 使用window.location进行跳转，确保页面完全刷新，避免路由问题
    window.location.href = '/nursing/healthCheck/stepInput';
  } catch (error) {
    console.error('页面跳转失败:', error);
    proxy?.$modal.msgError('页面跳转失败，请重试');
  }
}

/** 查看详情按钮操作 */
const handleDetail = (row: HealthCheckVO) => {
  // 这里使用只读模式查看健康监测详情
  try {
    window.location.href = `/nursing/healthCheck/stepInput?id=${row.id}&mode=view`;
  } catch (error) {
    console.error('查看详情失败:', error);
    proxy?.$modal.msgError('查看详情失败，请重试');
  }
}

onMounted(() => {
  getList();
});
</script>
